package com.hbnu.controller;

import com.hbnu.pojo.DormBuild;
import com.hbnu.pojo.PageModel;
import com.hbnu.pojo.Record;
import com.hbnu.pojo.User;
import com.hbnu.service.DormManagerService;
import com.hbnu.service.RecordService;
import com.hbnu.service.UserService;
import com.hbnu.service.impl.DormManagerServiceImpl;
import com.hbnu.service.impl.RecordServiceImpl;
import com.hbnu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/record.action")
public class RecordServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();
    RecordService recordService=new RecordServiceImpl();
    DormManagerService dormManagerService=new DormManagerServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");
        String id = req.getParameter("id");

        //获取当前登录的用户
        User userCurr = (User) req.getSession().getAttribute("session_user");

        if (action != null && "list".equals(action)) {
            //查询缺勤记录并展示
            Integer roleId = userCurr.getRoleId();
            List<DormBuild> buildList = new ArrayList<DormBuild>();
            if ("0".equals(roleId)) {
                buildList = dormManagerService.findAll();//超级管理员查询所有
            } else if ("1".equals(roleId)) {
                buildList = dormManagerService.findByUserId(userCurr.getId());//普通管理员 只能添加用户到其管理的楼栋
            }
            req.setAttribute("builds", buildList);

            String startDate = req.getParameter("startDate");
            String endDate = req.getParameter("endDate");
            String dormBuildId = req.getParameter("dormBuildId");
            String searchType = req.getParameter("searchType");
            String keyword = req.getParameter("keyword");
            String pageIndex = req.getParameter("pageIndex");

            //默认从第一行开始
            PageModel pageModel = new PageModel();
            if (pageIndex != null && !"".equals(pageIndex)) {
                pageModel.setPageIndex(Integer.parseInt(pageIndex));
            }

            //分页查询
            List<Record> records = recordService.findRecords(startDate, endDate, dormBuildId, searchType, keyword, userCurr, pageModel);

            //获取查询结果
            Integer totalNum = recordService.getTotalNum(startDate, endDate, dormBuildId, searchType, keyword, userCurr);
            req.setAttribute("totalNum", totalNum);
            req.setAttribute("startDate", startDate);
            req.setAttribute("endDate", endDate);
            req.setAttribute("dormBuildId", dormBuildId);
            req.setAttribute("searchType", searchType);
            req.setAttribute("keyword", keyword);
            req.setAttribute("pageIndex", pageModel.getPageIndex());
            req.setAttribute("records", records);
            req.setAttribute("mainRight", "/jsp/recordList.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);


        } else if (action != null && "preAdd".equals(action)) {
            req.setAttribute("mainRight", "/jsp/recordAddOrUpdate.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        } else if (action != null && "save".equals(action)) {
            String stuCode = req.getParameter("stuCode");
            String date = req.getParameter("date");
            String remark = req.getParameter("remark");

            User user = userService.findStuCodeAndManager(stuCode, userCurr);

            if (id != null && !"".equals(id)) {
                if (user != null) {
                    Record record = recordService.findById(Integer.parseInt(id));
                    try {
                        record.setDate(new SimpleDateFormat("yyyy-MM-dd").parse(date));
                        record.setRemark(remark);
                        record.setStudent_id(user.getId());
                        recordService.update(record);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    resp.sendRedirect(getServletContext().getContextPath() +
                            "/record.action?action=list");
                } else {
                    resp.sendRedirect(getServletContext().getContextPath() +
                            "/record.action?action=list");
                }
            } else {
                if (user != null) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date date1 = null;
                    try {
                        date1 = dateFormat.parse(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Record record = new Record();
                    record.setStudent_id(user.getId());
                    record.setDate(date1);
                    record.setDisabled(0);
                    record.setRemark(remark);

                    recordService.save(record);
                    resp.sendRedirect(getServletContext().getContextPath() +
                            "/record.action?action=list");
                } else {
                    req.setAttribute("error", "您没有添加该学号学生缺勤记录的权限！");
                    req.setAttribute("mainRight", "/jsp/recordAddOrUpdate.jsp");
                    req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);

                }
            }
        } else if (action != null && action.equals("preUpdate")) {
            Record record = recordService.findById(Integer.parseInt(id));

            User user = userService.findStuCodeAndManager(record.getUser().getStuCode(), userCurr);

            if (user == null) {
                resp.sendRedirect(getServletContext().getContextPath() +
                        "/record.action?action=list");
            } else {
                req.setAttribute("record", record);
                req.setAttribute("mainRight", "/jsp/recordAddOrUpdate.jsp");
                req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
            }
        } else if (action != null && action.equals("deleteOrAcive")) {
            String disabled = req.getParameter("disabled");

            Record record = recordService.findById(Integer.parseInt(id));
            record.setDisabled(Integer.parseInt(disabled));

            User user = userService.findStuCodeAndManager(record.getUser().getStuCode(), userCurr);

            if (user == null) {
                // 无删除激活权限
                resp.sendRedirect(getServletContext().getContextPath() +
                        "/record.action?action=list");
            } else {
                // 有删除激活权限
                recordService.update(record);
                // 跳转到缺勤记录列表页
                resp.sendRedirect(getServletContext().getContextPath() +
                        "/record.action?action=list");
            }
        }
    }
}
